package com.kitty.game.activity.service.task;

import com.kitty.common.utils.SpringUtils;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.activity.service.ActivityService;
import com.kitty.game.activity.service.task.xiulian.ShiJueZhenTaskHandler;
import com.kitty.game.activity.service.task.xiulian.XiuXingTaskHandler;
import com.kitty.game.base.service.BagService;
import com.kitty.game.boss.config.BossSet;
import com.kitty.game.boss.model.BossFightParam;
import com.kitty.game.boss.model.BossNpcParam;
import com.kitty.game.boss.model.BossParam;
import com.kitty.game.boss.service.NewBossService;
import com.kitty.game.config.NPC;
import com.kitty.game.config.TaskSet;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.npc.message.RespAutoWalk;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.task.message.vo.TaskInfo;
import com.kitty.game.task.model.product.TaskType;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.team.model.Member;
import com.kitty.game.team.model.Team;
import com.kitty.game.team.service.TeamService;
import com.kitty.game.utils.Const;
import com.kitty.listener.event.FightEndEvent;
import com.kitty.mina.message.MessagePusher;
import org.nutz.lang.util.NutMap;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**修行任务处理类*/
public abstract class XiuLianTaskHandler extends TaskActivityHandler {
    private static final List<String> SMALL_BOOS_NAMES = Arrays.asList("兑灵", "震灵", "坎灵", "离灵", "艮灵",
            "疯灵", "狂灵", "爆灵", "傲灵", "镜灵");

    /**最少组队人数*/
    private static final int MIN_TEAM_COUNT = 1;
    private static final String MESSAGE_TEMPLATE = "你的队伍成功领取{0}任务，#R请注意修行与十绝阵共用领取奖励次数#n。";
    private static final String NO_REWARD_TIP = "今日获得战斗奖励已达#R{0}#n次，无法获得奖励！";

    /**获得接取修炼任务所在的NPC id*/
    public abstract int getAcceptNpcId();
    public abstract String getXiuLianName();
    public abstract int getTaskIdAtNpc();
    public abstract int getAcceptMinLevel();
    public abstract String getAcceptTeamCountNotEnough();
    public abstract String getAcceptLevelNotEnough();
    public abstract String getAccepted();
    public abstract String getReaminCountNotEnough();
    public abstract String getFightTeamCountNotEnough();
    public abstract String getFightLevelNotEnough();
    public abstract String getNotAccepted();
    public abstract String getMessageTemplate();
    public abstract int getNpcBossCount();
    public abstract String getFightStartPrompt(NPC bossNpc);

    @Override
    public TaskSet getAcceptingTask(Role role, NPC npc) {
        return taskService.getTaskSet(getTaskIdAtNpc(), role);
    }

    @Override
    public String canAcceptTask(Role role, TaskSet taskSet, boolean auto) {
        int teamCount = teamService.getTeamCount(role);
        if (teamCount < MIN_TEAM_COUNT) {
            return MessageFormat.format(getAcceptTeamCountNotEnough(), MIN_TEAM_COUNT);
        }

        /**判断所有人等级是否满足*/
        StringBuilder levelNotEnoughNames = new StringBuilder();
        Team team = teamService.getTeam(role.getRoleId());
        ArrayList<Member> members = team.getList();
        for (Member member : members) {
            if (member == null) {continue;}
            if (member.isInTeam() == false) {continue;}

            if (member.getLevel() >= getAcceptMinLevel()) {continue;}

            if (levelNotEnoughNames.length() > 0) {
                levelNotEnoughNames.append("、");
            }
            levelNotEnoughNames.append(member.getName());
        }
        if (levelNotEnoughNames.length() > 0) {
            return MessageFormat.format(getAcceptLevelNotEnough(), levelNotEnoughNames, getAcceptMinLevel());
        }

        /**判断所有玩家是否已经接取*/
        boolean isMemberNotAccept = false;
        for (Member member : team.getList()) {
            if (member == null) {continue;}
            /**暂离的不用判断*/
            if (member.isInTeam() == false) {continue;}

            Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
            if (memberRole == null) {continue;}

            /**有一个成员没有接取时，就设置为true*/
            if (isAcceptedTask(memberRole) == false) {
                isMemberNotAccept = true;
                break;
            }
        }

        if (isMemberNotAccept == false) {
            return getAccepted();
        }

        Object isTip = role.getTalk().popChooseParam(Const.XIULIAN_NO_REWARD_TIP_KEY);
        if (isTip == null) {
            ActivityService activityService = SpringUtils.getBean(ActivityService.class);

            /**判断是否有成员没有次数了，有时弹出提示*/
            StringBuilder remainCountNotEnoughNames = new StringBuilder();
            for (Member member : team.getList()) {
                if (member == null) {continue;}
                /**暂离的不用判断*/
                if (member.isInTeam() == false) {continue;}

                Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
                if (memberRole == null) {continue;}

                int remainCount = activityService.getRemainCount(memberRole, ActivityType.XIU_XING_TASK);
                if (remainCount <= 0) {
                    if (remainCountNotEnoughNames.length() > 0) {
                        remainCountNotEnoughNames.append("、");
                    }
                    remainCountNotEnoughNames.append(member.getName());
                }
            }

            /**此时表示都没有次数*/
            if (remainCountNotEnoughNames.length() > 0) {
                return MessageFormat.format(getReaminCountNotEnough(), remainCountNotEnoughNames);
            }
        }

        return null;
    }

    /**是否已经接取修行任务*/
    private boolean isAcceptedTask(Role role) {
        if (getTaskSetByType(role) != null) {
            return true;
        }
        return false;
    }
    // 接了人物之后立刻寻路
    public void doAfterAccept(Role role, TaskSet taskSet) {
        super.doAfterAccept(role, taskSet);
        this.autoWalk(role, taskSet);
    }
    @Override
    public TaskInfo getTaskInfo(Role role, TaskSet taskSet) {
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.setTaskName(taskSet.getTaskName());
        ActivityService activityService = SpringUtils.getBean(ActivityService.class);
        if (activityService.getFinishCount(role, ActivityType.XIU_XING_TASK) < ActivityType.XIU_XING_TASK.getTotalCount()) {
            int doStep = activityService.getFinishCount(role, ActivityType.XIU_XING_TASK) + 1;
            taskInfo.setShow_name(taskSet.getTaskName() + "(" + doStep + "/" + ActivityType.XIU_XING_TASK.getTotalCount() + ")");
        } else {
            taskInfo.setShow_name(taskSet.getTaskName() + "("+ Const.FINISH_NAME+")");
        }
        taskInfo.setTaskInfo(taskSet.getTaskJieshao());
        taskInfo.setTaskZhiyin(taskSet.getTaskZhiyin());
        return taskInfo;
    }

    @Override
    public String getPrompt(NPC npc) {
        return MessageFormat.format(MESSAGE_TEMPLATE, getXiuLianName());
    }

    @Override
    public BossNpcParam newBossNpcParam(Role role, TaskSet taskSet) {
        return null;
    }

    @Override
    public String getNpcContent(Role role, NPC bossNpc) {
        return null;
    }

    @Override
    public String getNpcContentNotFight(Role role, NPC bossNpc) {
        /**判断是否队伍有3人*/
        TeamService teamService = SpringUtils.getBean(TeamService.class);
        int teamCount = teamService.getTeamCount(role);
        if (teamCount < MIN_TEAM_COUNT) {
            return MessageFormat.format(getFightTeamCountNotEnough(), MIN_TEAM_COUNT);
        }

        TaskSet taskSet = getTaskSetByBossNpc(role, bossNpc);
        if (taskSet == null) {
            /**理论上是不可能走到这里的，防止抓包*/
            return getNotAccepted();
        }

        /**判断所有人等级是否满足*/
        StringBuilder levelNotEnoughNames = new StringBuilder();
        Team team = teamService.getTeam(role.getRoleId());
        ArrayList<Member> members = team.getList();
        for (Member member : members) {
            if (member == null) {continue;}
            if (member.isInTeam() == false) {continue;}

            if (member.getLevel() >= getAcceptMinLevel()) {continue;}

            if (levelNotEnoughNames.length() > 0) {
                levelNotEnoughNames.append("、");
            }
            levelNotEnoughNames.append(member.getName());
        }
        if (levelNotEnoughNames.length() > 0) {
            return MessageFormat.format(getFightLevelNotEnough(), levelNotEnoughNames, getAcceptMinLevel());
        }

        return null;
    }

    @Override
    public void doStartFight(Role role, TaskSet taskSet, NPC bossNpc) {
        List<BossParam> bossParamList = newBossParamList(role, bossNpc);
        NewBossService bossService = SpringUtils.getBean(NewBossService.class);
        BossFightParam bossFightParam = new BossFightParam(bossParamList, getFightType(role),taskSet.getId(), bossNpc.getId());
        bossService.startFightToBoss(role, bossFightParam);

        /**发战斗开始的提示内容*/
        String fightStartPromp = getFightStartPrompt(bossNpc);
        if (fightStartPromp != null) {
            teamService.pushMessage(role, new RespMsg(fightStartPromp));
        }
    }

    private List<BossParam> newBossParamList(Role role, NPC npc) {
        List<BossParam> bossParamList = new ArrayList<>();
        int count = getNpcBossCount();

        /**npc对应的加在第1个*/
        NewBossService bossService = SpringUtils.getBean(NewBossService.class);
        BossSet bossSet = bossService.getBossSet(npc.getName());
        bossParamList.add(new BossParam(bossSet, npc.getName()));

        List<String> bossNames = new ArrayList<>();
        bossNames.addAll(SMALL_BOOS_NAMES);
        bossNames.remove(npc.getName());
        /**加count-1个*/
        for (int i=1; i<count; i++) {
            int index = ThreadLocalRandom.current().nextInt(bossNames.size());
            bossSet = bossService.getBossSet(bossNames.get(index));
            bossParamList.add(new BossParam(bossSet, bossSet.getName()));
        }

        return bossParamList;
    }

    @Override
    protected void addActivityFinishCount(Role role, TaskSet taskSet) {
        SpringUtils.getBean(ActivityService.class).addFinishCount(role, ActivityType.XIU_XING_TASK, 1);
    }

    @Override
    protected void giveReward(Role role, NutMap reward, TaskSet taskSet,int currPetId) {


        ActivityService activityService = SpringUtils.getBean(ActivityService.class);
        int finishCount = activityService.getFinishCount(role, ActivityType.XIU_XING_TASK);

        /**大于完成次数时，则不能再获得奖励*/
        if (finishCount > ActivityType.XIU_XING_TASK.getTotalCount()) {
            MessagePusher.pushMessage(role, new RespNotifyMiscEx(MessageFormat.format(NO_REWARD_TIP, ActivityType.XIU_XING_TASK.getTotalCount())));
            return ;
        }

        int step = ((finishCount-1) % 10 + 1);
        /**每10轮时*/
        if (step == 10) {
            // 奖励装备
            short roleLevel = role.getLevel();
            String temp = roleLevel + "";
            if (temp.length() == 3) {
                roleLevel = Short.parseShort(temp.substring(0, 2) + 0);
            } else {
                roleLevel = Short.parseShort(temp.substring(0, 1) + 0);
            }
            BagService bagService = SpringUtils.getBean(BagService.class);
            EquipService equipService = SpringUtils.getBean(EquipService.class);

            short newPos = bagService.getPos(role, false);
            if (newPos > 0) {
                equipService.getNotIdentifyEquip(roleLevel, role, newPos);
            }
        }
        int exp = new Double(role.getLevel() * reward.getInt("rewardExp", 0)
                * (finishCount * 0.1 + 1)).intValue();
        int money = new Double(reward.getInt("rewardMoney", 0)
                * ((finishCount * 0.1 + 1))).intValue();

        RoleService roleService = SpringUtils.getRoleService();
        roleService.addMoney(role, money);
        NutMap nutMap = role.getPropsStatus();
        int point = nutMap.getInt("role");
        if (nutMap.getInt("roleStatus") == 1 && point >= 4) {
            nutMap.setv("role", point - 4);
            role.save();
            roleService.addExp(role, exp * 2, role.getLevel(),currPetId);
        } else {
            roleService.addExp(role, exp, role.getLevel(),currPetId);
        }
    }

    @Override
    public void deleteTaskForSingle(Role role, TaskSet taskSet) {
        TaskSet taskSetByType = getTaskSetByType(role);
        if (taskSetByType == null) {
            taskSetByType = taskSet;
        }

        super.deleteTaskForSingle(role, taskSetByType);
    }

    @Override
    protected void doBeforeDelete(Role role, TaskSet taskSet) {
        pushOtherXiuLianTaskInfo(role, taskSet);
    }

    @Override
    protected void doAfterDelete(Role role, TaskSet taskSet) {
 //       String content = acceptTaskAuto(role, taskSet);
        Team team = teamService.getTeam(role.getRoleId());
        if (team != null && team.isLeader(role.getRoleId())) {
            String content = acceptTaskAuto(role, taskSet);
            if (content == null) {
                /**自动寻路战斗*/
                TaskSet newTaskSet = getTaskSetByType(role);
                autoWalk(role, newTaskSet);
            }
        }
    }
    // add tao
    // 是否移除任务框
    public boolean isDeleteTaskLogout() {
        return true;
    }
    // 如果队伍状态发生改变则移除任务框
    public boolean isDeleteTaskTeamChange() {
        return true;
    }
    // add:e

    @Override
    public boolean isCreateNpcForFight(TaskSet taskSet) {
        return false;
    }

    /**自动接取任务*/
    private String acceptTaskAuto(Role role, TaskSet taskSet) {
	TaskSet nextTaskSet = taskService.getNextTask(taskSet, role);
	return acceptTask(role, nextTaskSet, true);
    //    TaskSet nextTaskSet = taskService.getNextTask(taskSet, role);
	   /* TaskSet nextTaskSet = this.taskService.getNextTask(taskSet, role);*/
        // 【非常重要】这里必须再次设置为true，否则导致和已完成任务的队友组队，每做一次任务就需要重新领取
        // 对于单人和队长，才有资格接任务
       /* if (!this.teamService.isInTeam(role) || (this.teamService.isInTeam(role) && this.teamService.isTeamLeader(role))) {
            ActivityService activityService = SpringUtils.getBean(ActivityService.class);
            int remainCount = activityService.getRemainCount(role, ActivityType.XIU_XING_TASK);
            if (remainCount > 0)
                role.getTalk().pushChooseParam("xiulian_no_reward_tip", true);
            return this.acceptTask(role, nextTaskSet, true);
        }
        return "";*/
	   // return acceptTask(role, nextTaskSet, true);
    }

    /**自动寻路战斗*/
    private void autoWalk(Role role, TaskSet taskSet) {
        TaskInfo taskInfo = getTaskInfo(role, taskSet);
        if (taskInfo == null) {return ;}

        RespAutoWalk respAutoWalk = new RespAutoWalk();
        respAutoWalk.setTaskName(taskInfo.getTaskName());
        respAutoWalk.setDest(taskInfo.getTaskZhiyin());
        MessagePusher.pushMessage(role, respAutoWalk);
    }

    /**客户端更新其他的修炼任务*/
    private void pushOtherXiuLianTaskInfo(Role role, TaskSet taskSet) {
        XiuLianTaskHandler xiuLianTaskHandler = null;
        if (taskSet.getTaskType() == TaskType.XIU_XING) {
            xiuLianTaskHandler = SpringUtils.getBean(ShiJueZhenTaskHandler.class);
        } else {
            xiuLianTaskHandler = SpringUtils.getBean(XiuXingTaskHandler.class);
        }

        TaskSet otherTaskSet = xiuLianTaskHandler.getTaskSetByType(role);
        if (otherTaskSet == null) {
            return ;
        }

        TaskInfo taskInfo = xiuLianTaskHandler.getTaskInfo(role, otherTaskSet);
        if (taskInfo != null) {
            taskService.pushTaskInfo(role, taskInfo);
        }
    }

    @Override
    public void doFightFail(Role role, TaskSet taskSet, FightEndEvent fightEndEvent) {
        super.doFightFail(role, taskSet, fightEndEvent);
        teamService.memberHandleThreadLocal(role, memberRole -> SpringUtils.getRoleService().punishFightDead(memberRole));
    }
}
